//登陆路游
const express = require("express");

const route = express.Router();

//引入集合
const AdminModule = require("../mongoose/module/index");

//引入token封装
const { tokenEnCode, tokenDeCode } = require("../JWT/index");
route.use(express.json());
route.use(express.urlencoded());

route.post("/login", async (request, response) => {
  //获取参数
  const { adminName, passWord } = request.body;
  //登陆验证三种情形  账号对了密码没对 账号密码都错 账号密码都对
  //去数据库查找
  try {
    const loginRe = await AdminModule.findOne({
      adminName,
    });

    if (!loginRe) {
      return response.send({
        code: 201,
        message: "账户不存在",
        data: null,
      });
    }
    // 密码不对
    if (Number(loginRe.passWord) !== Number(passWord)) {
      return response.send({
        code: 202,
        message: "密码错误",
        data: null,
      });
    }
    //密码账号都正确 改变登陆状态
    const statusRe = await AdminModule.updateOne(
      {
        adminName,
      },
      {
        $set: { status: 1 },
      }
    );

    //赋予token
    response.send({
      code: 200,
      message: "登陆成功",
      data: {
        token: tokenEnCode(adminName),
      },
    });
  } catch (error) {
    response.send({
      code: 203,
      message: error.message,
      data: null,
    });
  }
});

module.exports = route;
